import base64
import pickle

from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from carts import constants
from goods.models import SKU


class CartVIew(APIView):
    """购物车"""
    def perform_authentication(self, request):
        """
        重写父类的用户验证方法,不在进入视图前就检查JWT
        :param request:
        :return:
        """
        pass

    def post(self, request):
        """
        添加购物车
        :param request:
        :return:
        """
        params = request.data
        skuid = params.get('sku_id')
        count = params.get('count')
        selected = params.get('selected', True)
        # 检查数据
        try:
            sku = SKU.objects.get(id = skuid)
        except Exception as e:
            return Response({'data':"商品查找失败..."})
        try:
            count = int(count)
        except Exception as e:
            return Response({'data': "传参不正确..."})

        # 验证用户
        try:
            user = request.user
        except Exception as e:
            user = None

        if user is not None and user.is_authenticated:
            # 用户已经登录,在redis中保存
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            # 记录购物车商品数量
            pl.hincrby('cart_{}'.format(user.id), skuid, count)
            # 记录购物车的勾选项
            # 勾选
            if selected:
                pl.sadd('cart_selected_{}'.format(user.id),skuid)
            pl.execute()
            return Response({'sku_id':skuid,
                             'count':count,
                             'selected':selected}, status=status.HTTP_201_CREATED)
        else:
            # 用户未登录, 在cookie中保存
            # {
            #     1001:{'count':10,'selected':true},
            #     ...
            # }
            # 使用pickle序列化购物车数据, pickle操作的是bytes类型
            cart = request.COOKIES.get('cart')
            if cart is not None:
                cart = pickle.loads(base64.b64decode(cart))
            else:
                cart = {}

            sku = cart.get(skuid)
            if sku:
                count += int(sku.get('count'))
            cart[skuid] = {
                'count': count,
                'selected': selected
            }
            cookie_cart = base64.b64encode(pickle.dumps(cart))
            response = Response({'sku_id':skuid,
                             'count':count,
                             'selected':selected}, status=status.HTTP_201_CREATED)
            response.set_cookie('cart',cookie_cart, max_age=constants.CART_COOKIE_EXPIRES)
            return response


    def get(self, request):
        """
        查询购物车数据
        :param request:
        :return:
        """
        try:
            user = request.user
        except Exception as e:
            user = None

        if user is not None and user.is_authenticated:
            # 用户已登录,从redis中获取数据
            redis_conn = get_redis_connection('cart')
            redis_cart = redis_conn.hgetall('cart_{}'.format(user.id))
            redis_selected = redis_conn.smembers('cart_selected_{}'.format(user.id))

            cart = {}
            for sku_id, count in redis_cart.items():
                cart[int(sku_id)] = {
                    'count':int(count),
                    'selected':sku_id in redis_selected
                }
        else:
            # 用户未登录, 从cookie中读取
            cart = request.COOKIES.get('cart')
            if cart:
                cart = pickle.load(base64.b64decode(cart))
            else:
                cart = {}

        # 遍历处理购物车数据
        skus = SKU.objects.filter(id__in=cart.keys())
        skus_list = []
        for sku in skus:
            sku_dict = {}
            sku_dict['id'] = sku.id
            sku_dict['count'] = cart[sku.id]['count']
            sku_dict['name']=sku.name
            sku_dict['default_image_url'] = sku.default_image_url
            sku_dict['price'] = sku.price
            sku_dict['selected'] = cart[sku.id]['selected']
            skus_list.append(sku_dict)

        return Response(skus_list)


    def put(self, request):
        """
        修改购物车数据
        :param request:
        :return:
        """
        params = request.data
        skuid = params.get('sku_id')
        count = params.get('count')
        selected = params.get('selected', True)
        # 检查数据
        try:
            sku = SKU.objects.get(id=skuid)
        except Exception as e:
            return Response({'data': "商品查找失败..."})
        try:
            count = int(count)
        except Exception as e:
            return Response({'data': "传参不正确..."})

        # 验证用户
        try:
            user = request.user
        except Exception as e:
            user = None

        if user is not None and user.is_authenticated:
            # 用户已经登录,在redis中保存
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            # 记录购物车商品数量
            pl.hincrby('cart_{}'.format(user.id), skuid, count)
            # 记录购物车的勾选项
            # 勾选
            if selected:
                pl.sadd('cart_selected_{}'.format(user.id),skuid)
            pl.execute()
            return Response({'sku_id':skuid,
                             'count':count,
                             'selected':selected}, status=status.HTTP_201_CREATED)
        else:
            # 用户未登录, 在cookie中保存
            # {
            #     1001:{'count':10,'selected':true},
            #     ...
            # }
            # 使用pickle序列化购物车数据, pickle操作的是bytes类型
            cart = request.COOKIES.get('cart')
            if cart is not None:
                cart = pickle.loads(base64.b64decode(cart))
            else:
                cart = {}

            sku = cart.get(skuid)
            if sku:
                count += int(sku.get('count'))
            cart[skuid] = {
                'count': count,
                'selected': selected
            }
            cookie_cart = base64.b64encode(pickle.dumps(cart))
            response = Response({'sku_id':skuid,
                             'count':count,
                             'selected':selected}, status=status.HTTP_201_CREATED)
            response.set_cookie('cart',cookie_cart, max_age=constants.CART_COOKIE_EXPIRES)
            return response


    def delete(self, request):
        """
        删除购物车数据
        :param request:
        :return:
        """
        params = request.data
        skuid = params.get('sku_id')
        # 检查数据
        try:
            sku = SKU.objects.get(id=skuid)
        except Exception as e:
            return Response({'data': "商品查找失败..."})

        # 验证用户
        try:
            user = request.user
        except Exception as e:
            user = None

        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            pl.hdel('cart_{}'.format(user.id), skuid)
            pl.srem('cart_selected_{}'.format(user.id), skuid)
            pl.execute()
            return Response(status=status.HTTP_204_NO_CONTENT)
        else:
            response = Response(status=status.HTTP_204_NO_CONTENT)

            # 使用pickle序列化购物车数据，pickle操作的是bytes类型
            cart = request.COOKIES.get('cart')
            if cart is not None:
                cart = pickle.loads(base64.b64decode(cart.encode()))
                if skuid in cart:
                    del cart[skuid]
                    cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()
                    # 设置购物车的cookie
                    # 需要设置有效期，否则是临时cookie
                    response.set_cookie('cart', cookie_cart, max_age=constants.CART_COOKIE_EXPIRES)
            return response

    def put(self, request):
        """
        修改全部选中状态
        :param request:
        :return:
        """
        params = request.data
        skuid = params.get('sku_id')
        count = params.get('count')
        selected = params.get('selected', True)
        # 检查数据
        try:
            sku = SKU.objects.get(id=skuid)
        except Exception as e:
            return Response({'data': "商品查找失败..."})
        try:
            count = int(count)
        except Exception as e:
            return Response({'data': "传参不正确..."})

        # 验证用户
        try:
            user = request.user
        except Exception as e:
            user = None

        if user is not None and user.is_authenticated:
            # 用户已经登录,在redis中保存
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            # 记录购物车商品数量
            pl.hincrby('cart_{}'.format(user.id), skuid, count)
            # 记录购物车的勾选项
            # 勾选
            if selected == True:
                pl.sadd('cart_selected_{}'.format(user.id), skuid)
            elif selected == False:
                pl.srem('cart_selected_{}'.format(user.id), skuid)
            pl.execute()
            return Response({'message': 'OK'}, status=status.HTTP_204_NO_CONTENT)
        else:
            # 用户未登录, 在cookie中保存
            # {
            #     1001:{'count':10,'selected':true},
            #     ...
            # }
            # 使用pickle序列化购物车数据, pickle操作的是bytes类型
            cart = request.COOKIES.get('cart')
            if cart is not None:
                cart = pickle.loads(base64.b64decode(cart))
            else:
                cart = {}

            sku = cart.get(skuid)
            if sku:
                count += int(sku.get('count'))
            cart[skuid] = {
                'count': count,
                'selected': selected
            }
            cookie_cart = base64.b64encode(pickle.dumps(cart))
            response = Response({'message': 'OK'}, status=status.HTTP_204_NO_CONTENT)
            response.set_cookie('cart', cookie_cart, max_age=constants.CART_COOKIE_EXPIRES)
            return response


class CartSelectAllView(APIView):
    """
    购物车全选
    """
    def perform_authentication(self, request):
        """
        重写父类的用户验证方法,不在进入视图前就检查JWT
        :param request:
        :return:
        """
        pass


    def put(self, request):
        """
        购物车全选/取消全选
        :param request:
        :return:
        """
        params = request.data
        selected = params.get('selected')

        # 检查参数
        if not isinstance(selected, bool):
            return Response({'message': '参数类型错误'},status=status.HTTP_400_BAD_REQUEST)

        try:
            user = request.user
        except Exception as e:
            user = None

        if user is not None and user.is_authenticated:
            # 用户已登录，在redis中保存
            redis_conn = get_redis_connection('cart')
            cart = redis_conn.hgetall('cart_%s' % user.id)
            sku_id_list = cart.keys()

            if selected:
                # 全选
                redis_conn.sadd('cart_selected_%s' % user.id, *sku_id_list)
            else:
                # 取消全选
                redis_conn.srem('cart_selected_%s' % user.id, *sku_id_list)
            return Response({'message': 'OK'})
        else:
            # cookie
            cart = request.COOKIES.get('cart')

            response = Response({'message': 'OK'})

            if cart is not None:
                cart = pickle.loads(base64.b64decode(cart.encode()))
                for sku_id in cart:
                    cart[sku_id]['selected'] = selected
                cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()
                # 设置购物车的cookie
                # 需要设置有效期，否则是临时cookie
                response.set_cookie('cart', cookie_cart, max_age=constants.CART_COOKIE_EXPIRES)

            return response


